<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{path:'/home'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 搜索框以及添加 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            clearable
            @clear="getUserList(true)"
            placeholder="请输入内容"
            v-model="queryInfo.query"
          >
            <el-button @click="getUserList(true)" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="addUserDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userList" stripe height="500px">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="userId" label="id"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="password" label="密码"></el-table-column>
        <el-table-column prop="userSex" label="性别"></el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isActive"
              active-text="是"
              active-value="是"
              inactive-text="否"
              inactive-value="否"
              @change="userStateChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="编辑用户" :enterable="false" placement="top">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="showEditUserDialog(scope.row.userId)"
              ></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除用户" :enterable="false" placement="top">
              <el-button
                size="mini"
                @click="removeUserById(scope.row.userId)"
                type="danger"
                icon="el-icon-delete"
              ></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="分配角色" :enterable="false" placement="top">
              <el-button size="mini" type="warning" icon="el-icon-setting"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.currentPage"
        :page-sizes="[5,10,15,20,30,50]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addUserDialogVisible"
      width="50%"
      @close="addUserDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="addUserForm"
        :rules="addUserFormRules"
        ref="addUserFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="QQ" prop="qq">
          <el-input v-model="addUserForm.qq"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户的对话框 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editUserDialogVisible"
      width="50%"
      @close="editUserDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="editUserForm"
        :rules="editUserFormRules"
        ref="editUserFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="QQ" prop="qq">
          <el-input v-model="editUserForm.qq"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱
    const checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 校验通过
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前页
        currentPage: 1,
        // 一页多少条数据
        pageSize: 5
      },
      // 用户列表
      userList: [],
      // 总数据条数
      total: 0,
      // 添加用户对话框
      addUserDialogVisible: false,
      // 添加的用户信息
      addUserForm: { username: '', password: '', email: '', qq: '' },
      // 添加用户表单校验规则
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名的长度在3~10个字符之间',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '密码的长度在6~15个字符之间',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ]
      },
      // 编辑用户对话框显示与隐藏
      editUserDialogVisible: false,
      editUserFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ]
      },
      editUserForm: {}
    }
  },
  computed: {
    convertStatus(isActive) {
      if (isActive === '是') {
        return true
      } else {
        return false
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 接收一个参数，true为返回的是首页
    async getUserList(pageOne) {
      if (pageOne) {
        this.queryInfo.currentPage = 1
      }
      const { data: res } = await this.$http.post('/user/users', this.queryInfo)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.userList = res.data.records
      this.total = res.data.total
    },
    // 监听pagesize改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getUserList()
    },
    // 监听当前页码改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.currentPage = newPage
      this.getUserList()
    },
    // 监听用户状态改变事件
    async userStateChanged(userInfo) {
      const { data: res } = await this.$http.put(
        `/user/${userInfo.userId}/state/${userInfo.isActive}`
      )
      if (res.meta.status !== 200) {
        userInfo.isActive = userInfo.isActive === '是' ? '否' : '是'
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    // 监听添加用户对话框关闭事件
    addUserDialogClosed() {
      this.$refs.addUserFormRef.resetFields()
    },
    // 添加用户
    addUser() {
      this.$refs.addUserFormRef.validate(async valid => {
        if (!valid) {
          // 校验未通过
          return
        }
        // 可以发起添加用户的请求
        const { data: res } = await this.$http.post('/user/user', {
          username: this.addUserForm.username,
          password: this.addUserForm.password,
          userEmail: this.addUserForm.email,
          userQq: this.addUserForm.qq
        })
        if (res.meta.status === 200) {
          this.$message.success(res.meta.msg)
          // 隐藏添加用户的对话框
          this.addUserDialogVisible = false
          // 刷新用户列表
          this.getUserList()
        } else {
          this.$message.error(res.meta.msg)
        }
      })
    },
    // 显示编辑用户对话框
    async showEditUserDialog(id) {
      const { data: res } = await this.$http.get('/user/user/' + id)
      if (res.meta.status === 200) {
        this.editUserForm = {
          id: res.data.userId,
          username: res.data.username,
          email: res.data.userEmail,
          qq: res.data.userQq
        }
        this.editUserDialogVisible = true
      } else {
        this.$message.error(res.meta.msg)
      }
    },
    // 编辑用户对话框关闭触发函数
    editUserDialogClosed() {
      this.editUserForm = {}
      this.$refs.editUserFormRef.resetFields()
    },
    // 编辑用户信息提交
    editUser() {
      this.$refs.editUserFormRef.validate(async valid => {
        // 校验没通过直接return
        if (!valid) {
          return
        }
        // 修改用户请求
        const { data: res } = await this.$http.put(
          '/user/user/' + this.editUserForm.id,
          {
            qq: this.editUserForm.qq,
            email: this.editUserForm.email
          }
        )
        if (res.meta.status === 200) {
          // 编辑成功
          this.$message.success(res.meta.msg)
          this.editUserDialogVisible = false
          this.getUserList()
        } else {
          // 编辑失败
          this.$message.error(res.meta.msg)
        }
      })
    },
    // 删除用户按钮触发
    async removeUserById(id) {
      // 询问用户是否删除用户
      const confirmResult = await this.$confirm(
        '是否删除该用户？',
        '删除用户',
        {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return
      }
      // 如果用户确认删除则返回值为confirm，如果取消则返回cancel
      const { data: res } = await this.$http.delete('/user/user/' + id)
      if (res.meta.status === 200) {
        this.$message.success(res.meta.msg)
        this.getUserList()
      } else {
        this.$message.error(res.meta.msg)
      }
    }
  }
}
</script>

<style lang='less' scoped>
</style>
